package com.ms.log.context;

import com.ms.log.config.ConfigParer;
import com.ms.log.config.XMLConfigParer;
import com.ms.log.logger.AbstractLogger;
import com.ms.log.logger.DefaultLogger;

import java.net.URL;

/**
 * @author zdh
 */
public class LogContextInitializer {

    final public static String DEFAULT_LOG_CONFIG_FILE = "little_orm_log.xml";

    public static final LoggerContext DEFAULT_LOGGER_CONTEXT = new LoggerContext(new DefaultLogger(AbstractLogger.LittleOrmLoggerName));

    /**
     * 初始化上下文
     */
    public static void autoConfig() {
        URL url = getConfigURL();
        if(url == null){
            System.err.println("little_orm_log.xml] file not found!");
            return ;
        }
        String urlString = url.toString();
        ConfigParer configParer = null;
        if(urlString.endsWith("xml")){
            configParer = new XMLConfigParer(url,DEFAULT_LOGGER_CONTEXT);
        }
        configParer.doPare();
    }

    private static URL getConfigURL(){
        URL url = null;
        ClassLoader classLoader = LogContextInitializer.class.getClassLoader();
        url = classLoader.getResource(DEFAULT_LOG_CONFIG_FILE);
        if(url != null){
            return url;
        }
        return null;
    }

    /**
     *  获取全局默认的LoggerContext
     */
    public static LoggerContext getDefaultLoggerContext(){
        return DEFAULT_LOGGER_CONTEXT;
    }
}
